package com.vdf.sisconsolid.mail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.vdf.sisconsolid.util.SisconsolidProperties;

public final class EmailSender {

	private static Logger log = Logger.getLogger(EmailSender.class);

	static String from = null;
	static String password = null;
	static Properties properties = System.getProperties();

	static {
		log.info("Inicializating Email Sender");
		from = SisconsolidProperties.getProperty("mail.smtp.user");
		password = SisconsolidProperties.getProperty("mail.smtp.password");
		// Get system properties
		// Setup mail server
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.user", from); // User name
		properties.put("mail.smtp.password", password); // password
		properties.put("mail.smtp.port", "587");
		properties.put("mail.smtp.auth", "true");
	}

	public void sendEmail(String to, String subject, String text,
			String attachmentFile) {

		// Get the default Session object.
		Session session = Session.getDefaultInstance(properties,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(from, password);
					}
				});

		try {
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(session);
			// Set From: header field of the header.
			message.setFrom(new InternetAddress(from));
			// Set To: header field of the header.
			message.addRecipients(Message.RecipientType.TO, to);
			// Set Subject: header field
			message.setSubject(subject);
			// Now set the actual message
			// message.setText(text);

			// Create the message part
			BodyPart messageBodyPart = new MimeBodyPart();
			// Fill the message
			messageBodyPart.setText(text);
			// Create a multipar message
			Multipart multipart = new MimeMultipart();
			// Set text message part
			multipart.addBodyPart(messageBodyPart);
			// Part two is attachment
			messageBodyPart = new MimeBodyPart();
			String filename = attachmentFile;
			DataSource source = new FileDataSource(filename);
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName(filename);
			multipart.addBodyPart(messageBodyPart);
			// Send the complete message parts
			message.setContent(multipart);
			// Send message
			Transport.send(message);
			log.debug("Sent message successfully....");
		} catch (MessagingException mex) {
			mex.printStackTrace();
			log.error("Error sending mail", mex);
		}

	}

	public static void main(String[] args) {
		// "visionpdg@gmail.com,sisconsolid@gmail.com,maguigal@hotmail.com"
		new EmailSender()
				.sendEmail(
						"visionpdg@gmail.com",
						SisconsolidProperties
								.getProperty("mail.consolidation.subject"),
						SisconsolidProperties
								.getProperty("mail.consolidation.text"),
						SisconsolidProperties
								.getProperty("consolidationPdfArchivesPath")
								+ "27.pdf");
	}

	public void sendConsolidationEmail(String to, String idConsolidation) {
		log.debug("sendConsolidationEmail, to " + to + ", idConsolidation "
				+ idConsolidation);
		Thread emailSendingThread = new EmailSendingThread(
				to,
				SisconsolidProperties.getProperty("mail.consolidation.subject"),
				SisconsolidProperties.getProperty("mail.consolidation.text"),
				SisconsolidProperties
						.getProperty("consolidationPdfArchivesPath")
						+ idConsolidation + ".pdf");
		emailSendingThread.start();
	}

	private class EmailSendingThread extends Thread {

		String to;
		String subject;
		String text;
		String attachmentPath;

		public EmailSendingThread(String to, String subject, String text,
				String attachmentPath) {
			this.to = to;
			this.subject = subject;
			this.text = text;
			this.attachmentPath = attachmentPath;
		}

		@Override
		public void run() {
			sendEmail(to, subject, text, attachmentPath);
		}
	}
}
